<!--
 * @Author: yumao 123456
 * @Date: 2025-08-20 15:19:06
 * @LastEditors: yumao 123456
 * @LastEditTime: 2025-09-09 10:02:05
 * @FilePath: \龙飞\src\views\model\operatorCheck\detail.vue
 * @Description: 审核详情页面
-->
<template>
  <div class="approval-detail">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <a-breadcrumb>
        <a-breadcrumb-item>
          <a-icon type="home" />
          <span>首页</span>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <a @click="goBackToList">模型审核</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>
          <a @click="goBackToList">{{ getTabName() }}</a>
        </a-breadcrumb-item>
        <a-breadcrumb-item>审核详情</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-spin :spinning="loading">
      <div v-if="detailData" class="detail-container">
        <!-- 审核结果 -->
        <div class="section-header">
          <a-icon type="check-circle" class="section-icon" />
          <span class="section-title">审核结果</span>
          <a-icon v-if="canEdit" type="edit" class="edit-icon-header" @click="toggleEditMode" title="编辑审核结果" />
        </div>
        <!-- 审核结果显示模式 -->
        <div v-if="!isEditMode" class="result-section">
          <!-- 待审核状态 -->
          <template v-if="detailData.approvalInfo.approvalStatus === '0'">
            <div class="result-item">
              <span class="result-label">申请状态</span>
              <a-tag
                :color="getStatusColor(detailData.approvalInfo.approvalStatus)"
                :class="['result-status', 'pending-status']">
                <a-icon type="clock-circle" />
                {{ getStatusText(detailData.approvalInfo.approvalStatus) }}
              </a-tag>
            </div>
          </template>

          <!-- 审核通过或不通过状态 -->
          <template v-else>
            <div class="result-item">
              <span class="result-label">审核结果</span>
              <a-tag
                :color="getStatusColor(detailData.approvalInfo.approvalStatus)"
                :class="['result-status', {
                  'rejection-status': detailData.approvalInfo.approvalStatus === '2',
                  'approval-status': detailData.approvalInfo.approvalStatus === '1'
                }]">
                <a-icon v-if="detailData.approvalInfo.approvalStatus === '2'" type="close-circle" />
                <a-icon v-else-if="detailData.approvalInfo.approvalStatus === '1'" type="check-circle" />
                {{ getStatusText(detailData.approvalInfo.approvalStatus) }}
              </a-tag>
            </div>
            <div class="result-item">
              <span class="result-label">审核理由</span>
              <span class="result-value">{{ detailData.approvalInfo.approvalReasons || '无审核理由' }}</span>

            </div>
          </template>
        </div>

        <!-- 审核编辑模式 -->
        <div v-if="isEditMode" class="edit-section">
          <div class="edit-item">
            <span class="edit-label">审核结果</span>
            <a-radio-group
              v-model="editForm.approvalStatus"
              class="approval-radio"
              :disabled="isApprovalStatusDisabled">
              <a-radio :value="1">通过</a-radio>
              <a-radio :value="2">不通过</a-radio>
            </a-radio-group>
          </div>
          <div class="edit-item">
            <span class="edit-label">审核理由</span>
            <a-textarea v-model="editForm.approvalReasons" placeholder="请输入审核理由" :rows="4" class="approval-textarea" />
          </div>
          <div class="edit-actions">
            <a-button @click="cancelEdit" class="cancel-btn">取消</a-button>
            <a-button type="primary" @click="confirmApproval" :loading="submitting" class="confirm-btn">
              确认
            </a-button>
          </div>
        </div>

        <!-- 申请理由 -->
        <div class="section-header">
          <a-icon type="exclamation-circle" class="section-icon" />
          <span class="section-title">申请理由</span>
        </div>
        <div class="error-section">
          <span class="error-text">{{ detailData.approvalInfo.applyReasons || '无申请理由' }}</span>
        </div>

        <!-- 模型详情 -->
        <div class="section-header">
          <a-icon type="file-text" class="section-icon" />
          <span class="section-title">模型详情</span>
        </div>
        <div class="model-details">
          <a-table
            :columns="modelColumns"
            :data-source="modelData"
            :pagination="{ showSizeChanger: false, showQuickJumper: false, hideOnSinglePage: false }"
            size="small"
            class="model-table" />
        </div>

        <!-- 输入参数 -->
        <div class="section-header">
          <a-icon type="import" class="section-icon" />
          <span class="section-title">输入参数</span>
        </div>
        <div class="params-section">
          <a-table
            :columns="inputColumns"
            :data-source="inputData"
            :pagination="{ showSizeChanger: false, showQuickJumper: false, hideOnSinglePage: false }"
            size="small"
            class="params-table" />
        </div>

        <!-- 输出参数 -->
        <div class="section-header">
          <a-icon type="export" class="section-icon" />
          <span class="section-title">输出参数</span>
        </div>
        <div class="params-section">
          <a-table
            :columns="outputColumns"
            :data-source="outputData"
            :pagination="{ showSizeChanger: false, showQuickJumper: false, hideOnSinglePage: false }"
            size="small"
            class="params-table" />
        </div>

      </div>
    </a-spin>

    <!-- 测试弹框 -->
    <TestPop
      :visible="testVisible"
      :model-data="currentTestModel"
      @close="handleTestClose"
      @test-complete="handleTestComplete" />
  </div>
</template>

<script>
import { approvalDetail, approval, downloadModelPDF } from '@/api/operatorCheck'
import moment from 'moment'
import TestPop from '@/components/TestPop'

export default {
  name: 'ApprovalDetail',
  components: {
    TestPop
  },
  data() {
    return {
      loading: false,
      detailData: null,
      inputData: [],
      outputData: [],
      modelData: [],
      isEditMode: false,
      submitting: false,
      editForm: {
        approvalStatus: 1,
        approvalReasons: ''
      },
      isApprovalStatusDisabled: false,
      // 测试弹框相关
      testVisible: false,
      currentTestModel: null,
      // 模型详情表格列
      modelColumns: [
        {
          title: '模型编号',
          dataIndex: 'modelId',
          key: 'modelId',
        },
        {
          title: '模型名称',
          dataIndex: 'modelName',
          key: 'modelName',
        },
        {
          title: '模型版本',
          dataIndex: 'version',
          key: 'version',
        },
        {
          title: '模型类型',
          dataIndex: 'modelType',
          key: 'modelType',
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          customRender: (text, record) => {
            return (
              <div>
                <a-button type="link" size="small" onClick={() => this.downloadDocument(record)}>下载文档</a-button>
                <a-divider type="vertical" />
                <a-button type="link" size="small" onClick={() => this.testModel(record)}>测试</a-button>
              </div>
            )
          }
        },
      ],
      // 输入参数表格列
      inputColumns: [
        {
          title: '字段名',
          dataIndex: 'name',
          key: 'name',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '显示名',
          dataIndex: 'dName',
          key: 'dName',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '变量数据类型',
          dataIndex: 'datatype',
          key: 'datatype',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '变量字段类型',
          dataIndex: 'type',
          key: 'type',
          width: 150,
          customRender: (text) => text || '-'
        },
      ],
      // 输出参数表格列
      outputColumns: [
        {
          title: '字段名',
          dataIndex: 'name',
          key: 'name',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '显示名',
          dataIndex: 'dName',
          key: 'dName',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '变量数据类型',
          dataIndex: 'datatype',
          key: 'datatype',
          width: 150,
          customRender: (text) => text || '-'
        },
        {
          title: '变量字段类型',
          dataIndex: 'type',
          key: 'type',
          width: 150,
          customRender: (text) => text || '-'
        },
      ],
    }
  },
  computed: {
    // 根据来源参数判断是否可以编辑审核结果
    canEdit() {
      const source = this.$route.query.source
      // 只有来源为'myReview'（我审核的）时才能修改审核结果
      return source === 'myReview'
    }
  },
  created() {
    this.loadDetail()
  },
  methods: {
    getTabName() {
      const source = this.$route.query.source
      if (source === 'mySubmit') {
        return '我提交的'
      } else if (source === 'myReview') {
        return '我审核的'
      }
      return '模型审核'
    },
    async loadDetail() {
      try {
        this.loading = true
        const approvalId = this.$route.query.approvalId
        if (!approvalId) {
          this.$message.error('缺少审核ID参数')
          return
        }

        const response = await approvalDetail({ approvalId })
        if (response.success && response.data) {
          this.detailData = response.data
          this.processInputData()
          this.processOutputData()
          this.processModelData()
        } else {
          this.$message.error(response.message || '获取详情失败')
        }
      } catch (error) {
        console.error('获取审核详情失败:', error)
        this.$message.error('获取详情失败')
      } finally {
        this.loading = false
      }
    },
    processInputData() {
      if (this.detailData && this.detailData.modelInfo && this.detailData.modelInfo.inputData) {
        try {
          this.inputData = JSON.parse(this.detailData.modelInfo.inputData)
        } catch (error) {
          console.error('解析输入数据失败:', error)
          this.inputData = []
        }
      } else {
        this.inputData = []
      }
    },
    processOutputData() {
      if (this.detailData && this.detailData.modelInfo && this.detailData.modelInfo.outputData) {
        try {
          this.outputData = JSON.parse(this.detailData.modelInfo.outputData)
        } catch (error) {
          console.error('解析输出数据失败:', error)
          this.outputData = []
        }
      } else {
        this.outputData = []
      }
    },
    processModelData() {
      if (this.detailData.modelInfo) {
        this.modelData = [{
          key: '1',
          modelId: this.detailData.modelInfo.uuid || '-',
          modelName: this.detailData.modelInfo.name || '-',
          version: this.detailData.modelInfo.version || '-',
          modelType: this.getModelTypeText(this.detailData.modelInfo.modelType) || '-',
          description: this.detailData.modelInfo.description || '-',
          action: '查看'
        }]
      }
    },
    getFlowTypeText(type) {
      const typeMap = {
        '00': 'Python删除',
        '01': 'Python上线',
        '02': 'Python下线',
        '03': 'PMML删除',
        '04': 'PMML上线',
        '05': 'PMML下线',
        '06': '评分卡删除',
        '07': '评分卡上线',
        '08': '评分卡下线',
        '20': '模型删除',
      }
      return typeMap[type] || type
    },
    getStatusText(status) {
      const statusMap = {
        '0': '待审核',
        '1': '通过',
        '2': '不通过',
      }
      return statusMap[status] || '未知状态'
    },
    getStatusColor(status) {
      const colorMap = {
        '0': 'orange', // 待审核使用橙色，更加醒目
        '1': 'success',
        '2': 'red', // 使用更明显的红色
      }
      return colorMap[status] || 'default'
    },
    getModelTypeText(type) {
      const typeMap = {
        'GM': '评分卡',
        'J': 'PMML',
        'P': 'Python',
      }
      return typeMap[type] || type
    },
    formatTime(timestamp) {
      if (!timestamp) return '-'
      return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },
    goBackToList() {
      // 根据来源参数返回到对应的tab
      const source = this.$route.query.source
      let activeTab = 'mySubmit' // 默认tab

      // 根据来源设置对应的tab
      if (source === 'mySubmit') {
        activeTab = 'mySubmit' // 我申请的
      } else if (source === 'myReview') {
        activeTab = 'myReview' // 我审核的
      }

      // 返回到模型审核页面并设置对应tab
      this.$router.push({
        path: '/model/operatorCheck',
        query: {
          activeTab: activeTab
        }
      })
    },
    toggleEditMode() {
      this.isEditMode = !this.isEditMode
      if (this.isEditMode) {
        // 进入编辑模式时，初始化表单数据
        this.editForm.approvalStatus = parseInt(this.detailData.approvalInfo.approvalStatus) || 1
        this.editForm.approvalReasons = this.detailData.approvalInfo.approvalReasons || ''
        // 如果当前审核状态已经是通过或不通过，则禁用审核结果选择
        const currentStatus = this.detailData.approvalInfo.approvalStatus
        this.isApprovalStatusDisabled = currentStatus === '1' || currentStatus === 1 || currentStatus === '2' || currentStatus === 2
      }
    },
    cancelEdit() {
      this.isEditMode = false
      // 重置表单数据
      this.editForm = {
        approvalStatus: 1,
        approvalReasons: ''
      }
      this.isApprovalStatusDisabled = false
    },
    async confirmApproval() {
      try {
        this.submitting = true
        const approvalId = this.$route.query.approvalId

        const params = {
          approvalId: approvalId,
          approvalReasons: this.editForm.approvalReasons,
          approvalStatus: this.editForm.approvalStatus
        }

        const response = await approval(params)
        if (response.success) {
          this.$message.success('审核操作成功')
          this.isEditMode = false
          // 重新加载详情数据
          await this.loadDetail()
        } else {
          this.$message.error(response.message || '审核操作失败')
        }
      } catch (error) {
        console.error('审核操作失败:', error)
        this.$message.error('审核操作失败')
      } finally {
        this.submitting = false
      }
    },
    async downloadDocument(record) {
      try {
        // 显示加载提示
        const loadingMessage = this.$message.loading('正在下载文档...', 0)

        // 使用模型信息中的实际参数
        const params = {
          modelUuid: this.detailData?.modelInfo?.uuid || record.modelId || '2024100975614814',
          version: this.detailData?.modelInfo?.version || record.version || 'V1'
        }

        // 调用封装的下载方法
        const result = await downloadModelPDF(params, {
          defaultFileName: `模型文档_${params.modelUuid}_${params.version}.pdf`
        })

        // 关闭加载提示
        loadingMessage()

        // 显示成功消息
        this.$message.success(`文档下载成功: ${result.fileName}`)
      } catch (error) {
        // 关闭加载提示
        this.$message.destroy()

        // 错误处理
        console.error('下载文档失败:', error)

        // 根据错误类型显示不同的错误消息
        if (error.message && error.message.includes('网络')) {
          this.$message.error('网络连接失败，请检查网络后重试')
        } else if (error.message && error.message.includes('权限')) {
          this.$message.error('没有下载权限，请联系管理员')
        } else {
          this.$message.error('文档下载失败，请稍后重试')
        }
      }
    },
    testModel(record) {
      // 设置当前测试的模型数据
      this.currentTestModel = {
        modelUuid: this.detailData?.modelInfo?.uuid || record.modelId,
        modelName: this.detailData?.modelInfo?.name || record.modelName,
        version: this.detailData?.modelInfo?.version || record.version,
        modelType: this.detailData?.modelInfo?.modelType || record.modelType,
      }
      // 显示测试弹框
      this.testVisible = true
    },

    // 关闭测试弹框
    handleTestClose() {
      this.testVisible = false
      this.currentTestModel = null
    },
    // 测试完成回调
    handleTestComplete(testParams) {
      console.log('测试完成:', testParams)
      this.$message.success('模型测试完成')
      // this.testVisible = false
    },
  },
}
</script>

<style lang="less" scoped>
.approval-detail {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .breadcrumb-section {
    margin-bottom: 20px;
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    :deep(.ant-breadcrumb) {
      font-size: 14px;

      .ant-breadcrumb-link {
        color: #666;

        a {
          color: #1890ff;
          cursor: pointer;
          transition: color 0.3s;
          text-decoration: none;

          &:hover {
            color: #40a9ff;
          }
        }
      }

      .ant-breadcrumb-separator {
        color: #d9d9d9;
      }
    }
  }

  .detail-container {
    max-width: 1200px;
    margin: 0 auto;
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .section-header {
    display: flex;
    align-items: center;
    margin: 24px 0 16px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #e8e8e8;
    justify-content: flex-start;

    &:first-child {
      margin-top: 0;
    }

    .section-icon {
      font-size: 16px;
      color: #1890ff;
      margin-right: 8px;
    }

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      // flex: 1;
    }

    .edit-icon-header {
      font-size: 16px;
      color: #1890ff;
      cursor: pointer;
      transition: all 0.3s ease;
      margin-left: 8px;
      padding: 6px;
      border-radius: 4px;
      background: rgba(24, 144, 255, 0.1);
      border: 1px solid rgba(24, 144, 255, 0.3);
      box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);
      position: relative;
      &::before {
        content: '';
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        border: 2px solid #1890ff;
        border-radius: 6px;
        opacity: 0;
        animation: edit-pulse 2s infinite;
      }

      &:hover {
        color: #fff;
        background: #1890ff;
        border-color: #1890ff;
        box-shadow: 0 4px 8px rgba(24, 144, 255, 0.4);
        transform: translateY(-1px);

        &::before {
          opacity: 0.6;
        }
      }
    }
  }

  .result-section {
    margin-bottom: 24px;

    .result-item {
      display: flex;
      align-items: center;
      padding: 12px 0;
      border-bottom: 1px solid #f0f0f0;

      &:last-child {
        border-bottom: none;
      }

      .result-label {
        width: 100px;
        color: #666;
        font-size: 14px;
      }

      .result-value {
        flex: 1;
        color: #333;
        margin-right: 8px;
      }

      .result-status {
        margin-left: 12px;
      }

      .link-icon {
        color: #1890ff;
        cursor: pointer;
        margin-left: 8px;
      }
    }
  }

  .edit-section {
    margin-bottom: 24px;
    padding: 20px;
    background: #fafafa;
    border: 1px solid #e8e8e8;
    border-radius: 6px;

    .edit-item {
      margin-bottom: 16px;

      &:last-of-type {
        margin-bottom: 20px;
      }

      .edit-label {
        display: block;
        margin-bottom: 8px;
        color: #333;
        font-size: 14px;
        font-weight: 500;
      }

      .approval-radio {
        :deep(.ant-radio-wrapper) {
          margin-right: 16px;
        }
      }

      .approval-textarea {
        width: 100%;
        resize: vertical;
      }
    }

    .edit-actions {
      text-align: right;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #e8e8e8;

      .cancel-btn {
        margin-right: 12px;
      }

      .confirm-btn {
        min-width: 80px;
      }
    }
  }

  .error-section {
    padding: 12px;
    background: #f6f6f6;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    margin-bottom: 24px;

    .error-text {
      color: #666;
      font-size: 14px;
    }
  }

  .model-details,
  .params-section {
    margin-bottom: 24px;

    .model-table,
    .params-table {
      border: 1px solid #e8e8e8;
      border-radius: 4px;

      :deep(.ant-table-thead > tr > th) {
        background: #fafafa;
        border-bottom: 1px solid #e8e8e8;
        border-right: 1px solid #e8e8e8;
        font-weight: 600;
        color: #333;
        padding: 12px 16px;

        &:last-child {
          border-right: none;
        }
      }

      :deep(.ant-table-tbody > tr > td) {
        padding: 12px 16px;
        border-bottom: 1px solid #f0f0f0;
        border-right: 1px solid #f0f0f0;

        &:last-child {
          border-right: none;
        }
      }

      :deep(.ant-table-tbody > tr:hover > td) {
        background: #f5f5f5;
      }

      :deep(.ant-table-tbody > tr:last-child > td) {
        border-bottom: 1px solid #e8e8e8;
      }
    }
  }

  .action-section {
    text-align: center;
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #e8e8e8;

    .back-button {
      padding: 8px 24px;
      border: 1px solid #d9d9d9;
      border-radius: 4px;
      background: #fff;
      color: #333;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #1890ff;
        color: #1890ff;
      }
    }
  }

  // 审核通过状态特殊样式
  .approval-status {
    background-color: #52c41a !important;
    border-color: #52c41a !important;
    color: #fff !important;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
    animation: pulse-green 2s infinite;

    .anticon {
      margin-right: 4px;
    }
  }

  // 审核不通过状态特殊样式
  .rejection-status {
    background-color: #ff4d4f !important;
    border-color: #ff4d4f !important;
    color: #fff !important;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
    animation: pulse-red 2s infinite;

    .anticon {
      margin-right: 4px;
    }
  }

  // 待审核状态特殊样式
  .pending-status {
    background-color: #fa8c16 !important;
    border-color: #fa8c16 !important;
    color: #fff !important;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(250, 140, 22, 0.3);
    animation: pulse-orange 2s infinite;

    .anticon {
      margin-right: 4px;
    }
  }

  .result-status {
    font-size: 14px;
    padding: 6px 14px;
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.3s ease;

    .anticon {
      margin-right: 4px;
    }
  }

  // 绿色脉冲动画效果（审核通过）
  @keyframes pulse-green {
    0% {
      box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
      transform: scale(1);
    }

    50% {
      box-shadow: 0 4px 16px rgba(82, 196, 26, 0.5);
      transform: scale(1.02);
    }

    100% {
      box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);
      transform: scale(1);
    }
  }

  @keyframes edit-pulse {
    0% {
      transform: scale(1);
      opacity: 0;
    }
    50% {
      transform: scale(1.1);
      opacity: 0.6;
    }
    100% {
      transform: scale(1);
      opacity: 0;
    }
  }

  // 红色脉冲动画效果（审核不通过）
  @keyframes pulse-red {
    0% {
      box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
      transform: scale(1);
    }

    50% {
      box-shadow: 0 4px 16px rgba(255, 77, 79, 0.5);
      transform: scale(1.02);
    }

    100% {
      box-shadow: 0 2px 8px rgba(255, 77, 79, 0.3);
      transform: scale(1);
    }
  }

  // 橙色脉冲动画效果（待审核）
  @keyframes pulse-orange {
    0% {
      box-shadow: 0 2px 8px rgba(250, 140, 22, 0.3);
      transform: scale(1);
    }

    50% {
      box-shadow: 0 4px 16px rgba(250, 140, 22, 0.5);
      transform: scale(1.02);
    }

    100% {
      box-shadow: 0 2px 8px rgba(250, 140, 22, 0.3);
      transform: scale(1);
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    padding: 12px;

    .detail-container {
      padding: 16px;
    }

    .result-item {
      flex-direction: column;
      align-items: flex-start;
      gap: 8px;

      .result-label {
        width: auto;
        font-weight: 600;
      }
    }
  }
}
</style>
